import time
from django.contrib import auth
from django.conf import settings


class AutoLogoutMiddleware:
    '''
    控制自动注销的中间件
    '''
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        if request.user.is_superuser or request.user.is_staff:
            # 不注销工作人员和管理员
            pass
        elif request.user.is_authenticated:
            # 用户登录的话
            last_active_time = request.session.get('last_active_time')
            if last_active_time is not None:
                # session有记录
                elapsed = time.time() - last_active_time
                if elapsed > settings.AUTO_LOGOUT_LIMIT * 60:
                    del request.session['last_active_time']
                    # 长时间没有操作，注销登陆，清理session
                    auth.logout(request)
                else:
                    # 重新设置活跃时间
                    request.session['last_active_time'] = int(time.time())
            else:
                # session中没有记录
                request.session['last_active_time'] = int(time.time())
        else:
            # 用户未登陆，删除对应记录
            if 'last_active_time' in request.session:
                del request.session['last_active_time']
                
        response = self.get_response(request)
        return response
